<?php
/**
 * Created by PhpStorm.
 * User: 宋春宝
 * Date: 2018/9/11
 * Time: 16:37
 */

namespace app\admin\controller;


use think\Controller;
use think\Request;

class Work extends Controller
{
    /**
     * 创建工单
     * @param Request $request
     * @return array
     */
    public function add(Request $request){
        $input = $request->param();

        $msg = $this->validate($input,'app\admin\validate\Dispatch');
        if($msg!='true'){
            return ['code'=>0,'msg'=>$msg];
        }
        $input['state_id'] = 10;
        $input['number'] = date('YmdHis').rand(100,999);
        $row = db('works')->insertGetId($input);
        if($row)
            return ['code'=>1,'msg'=>'提交成功'];
        return ['code'=>0,'msg'=>'提交失败'];
    }

    /**
     * 查询工单状态
     * @param Request $request
     * @return array
     */
    public function query(Request $request){
        $no = $request->param('no');
        if(empty($no)) return json(['code'=>0,'msg'=>'参数错误']);
        $info = db('works')->alias('w')
            ->where('w.number',$no)
            ->join('state st','st.id=w.state_id','left')
            ->join('dispatch dp','dp.works_id=w.id','left')
            ->field(['w.state_id','st.state_name','w.id','dp.id as dispatch_id'])
            ->find();
        if(!$info)return json(['code'=>0,'msg'=>'没有找到工单信息']);
        if($info['state_id']!=12&&$info['state_id']!=13){
            $dis = db('dispatch_flow')->where('dispatch_id',$info['dispatch_id'])->order('id','desc')->select();
            return json(['code'=>1,'msg'=>'','data'=>$dis]);
        }
        if($info['state_id']==14) return json(['code'=>0,'msg'=>'该工单已关闭']);
        return json(['code'=>0,'msg'=>'该工单在等待派单','data'=>'']);
    }
}